/*
 * 文件名               :  Toolkit.java
 * 用途                    :  工具类,用于创建唯一的Id,安静关闭Socket等
 * 最后修改日期:  $LastChangedDate: 2009-09-07 13:35:47 +0000 (Mon, 07 Sep 2009) $
 * 最后修改者     :  $LastChangedBy: wendal1985@gmail.com $
 * 创建者               :  Wendal Chen <wendal1985@gmail.com>
 */
package com.wendal.java.preproxy.util;

import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Random;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class Toolkit {
	
	private static Random random = new Random();
	
	
	
	public static String creatdID(Object obj){
		if(obj == null) obj = new Object();
		String str = ""+System.nanoTime()+"_" +obj.hashCode() +"_" + random.nextInt();
		return Base64.encode(str.getBytes());
	}



	public static void close(Socket socket) {
		if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					// Do noting
				}
		}
	}
	
	public static String getLocalhostIp(){
		try {
			Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
			InetAddress ia = null;
			while(nis.hasMoreElements()){
				NetworkInterface ni = (NetworkInterface)nis.nextElement();
				Enumeration<InetAddress> ias = ni.getInetAddresses();
				while(ias.hasMoreElements()){
					ia = ias.nextElement();
					if(ia instanceof Inet6Address) 
						continue;//skip ipv6
					if(ia.getHostAddress().startsWith("127."))
						continue;
					if(ia.getHostAddress().startsWith("192.168.1."))
						continue;
					return ia.getHostAddress();
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return "jperl.qicq.net";
	}
}

